/*
 * @Author: Await
 * @Date: 2025-02-23 11:38:32
 * @LastEditors: Await
 * @LastEditTime: 2025-02-23 20:23:09
 * @Description: 请填写简介
 */
import * as vscode from 'vscode';
import { DotNetDebugSession } from './debugger/debugger';

// 全局变量用于跟踪扩展状态
let debugAdapterDisposable: vscode.Disposable | undefined;
let isRegistered = false;

// 调试适配器类型常量
const DEBUG_TYPE = 'cursor-coreclr';

// 输出通道
let outputChannel: vscode.OutputChannel;

export async function activate(context: vscode.ExtensionContext) {
    // 创建输出通道
    outputChannel = vscode.window.createOutputChannel('Cursor C# Debug');
    context.subscriptions.push(outputChannel);

    try {
        outputChannel.appendLine('Cursor C# Debug 扩展开始激活');
        outputChannel.appendLine(`扩展路径: ${context.extensionPath}`);

        // 确保在注册新的之前注销旧的
        await deregisterDebugAdapter();

        // 注册新的调试适配器工厂
        if (!isRegistered) {
            outputChannel.appendLine('正在注册调试适配器工厂...');

            try {
                debugAdapterDisposable = vscode.debug.registerDebugAdapterDescriptorFactory(DEBUG_TYPE, {
                    createDebugAdapterDescriptor: (_session: vscode.DebugSession) => {
                        outputChannel.appendLine('创建新的调试适配器实例');
                        return new vscode.DebugAdapterInlineImplementation(new DotNetDebugSession());
                    }
                });

                // 将注册添加到订阅列表
                context.subscriptions.push(debugAdapterDisposable);
                isRegistered = true;
                outputChannel.appendLine('调试适配器注册成功');
            } catch (err) {
                outputChannel.appendLine(`调试适配器注册失败: ${err}`);
                throw err;
            }
        } else {
            outputChannel.appendLine('调试适配器已经注册，跳过注册步骤');
        }
    } catch (error) {
        outputChannel.appendLine(`扩展激活失败: ${error}`);
        // 确保清理任何部分注册
        await deregisterDebugAdapter();
        throw error;
    }
}

async function deregisterDebugAdapter() {
    if (debugAdapterDisposable) {
        try {
            outputChannel.appendLine('正在注销现有调试适配器...');
            debugAdapterDisposable.dispose();
            debugAdapterDisposable = undefined;
            isRegistered = false;
            // 给系统一些时间来清理旧的注册
            await new Promise(resolve => setTimeout(resolve, 100));
            outputChannel.appendLine('调试适配器注销成功');
        } catch (error) {
            outputChannel.appendLine(`调试适配器注销失败: ${error}`);
            throw error;
        }
    } else {
        outputChannel.appendLine('没有找到现有的调试适配器注册');
    }
}

export async function deactivate() {
    outputChannel.appendLine('扩展开始停用');
    await deregisterDebugAdapter();
    outputChannel.appendLine('扩展停用完成');
} 